import { useI18n } from '@/hooks/web/useI18n'
import { reactive, UnwrapRef, nextTick } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'

const { t } = useI18n()
import { ActionButtonsTemplate } from '@/api/global/types'
import { ElButton, ElIcon, ElUpload } from 'element-plus'
import { UploadItem } from '@/api/payment/types'
import { createPreViewDialogStoreType } from '@/store/modules/preViewDialog'
import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'
import { Close } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile/index.vue'
import { useUserStore } from '@/store/modules/user'
import { createImageViewer } from '@/components/ImageViewer'
import dayjs from 'dayjs'

const { required } = useValidator()

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}
const userStore = useUserStore()
export default function (
  actionButtonsTemplate?: ActionButtonsTemplate,
  operatorList?: UnwrapRef<any>,
  examine?: UnwrapRef<any>,
  fieldEnum?: any,
  showUploadProof?: UnwrapRef<any>,
  productPreViewStore?: createPreViewDialogStoreType,
  proofList?: UnwrapRef<Array<Record<string, any>>>,
  ProofArr?: UnwrapRef<UploadItem[]>,
  tableDialogStoreID?: string,
  tableDialogCurdSchema?: CrudSchema[],
  showChoicePurchase?: UnwrapRef<any>,
  setValues?: UnwrapRef<any>,
  attachmentArr?: UnwrapRef<any>,
  statusList?: UnwrapRef<any>,
  uploading?: (status: boolean) => void,
  setProofList?: (arr: Array<Record<string, any>>) => void,
  setProofListValue?: (obj: Record<string, any>) => void,
  formMethods?: any
) {
  const paytypeOption = reactive(createOptions(fieldEnum?.pay_type || {}))
  const paymentaccountOption = reactive(createOptions(fieldEnum?.payment_account || {}))
  // const paystatusOption = reactive(createOptions(fieldEnum?.pay_status || {}))
  // const statusOption = reactive(createOptions(fieldEnum?.status || {}))
  const statusOption = reactive(createOptions(statusList?.status || {}))
  const tableDialogStore = useTableDialogStore(tableDialogStoreID)

  // 多文件上传计数器
  let uploadingCount = 0

  // 检查是否所有文件上传完成
  const checkUploadComplete = () => {
    if (uploadingCount <= 0) {
      uploading?.(false)
    }
  }

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection',
        selectable: (row: Record<string, any>) => {
          return [1, 4].includes(row.status) && userStore.getUserInfo?.id == row.creator
        }
      }
    },
    {
      field: 'id',
      label: t('payment.id'),
      align: 'center',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'purchase_no',
      label: t('payment.purchase_no'),
      search: {
        hidden: false
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      },
      detail: {
        hidden: false
      }
    },
    {
      field: 'total_amount',
      label: t('payment.total_amount'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: true
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      },
      detail: {
        hidden: false
      }
    },
    {
      field: 'payno',
      label: t('payment.payno'),
      search: {
        // hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: true
        },
        hidden: examine
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'purchaseid',
      label: t('payment.purchaseid'),
      form: {
        hidden: showChoicePurchase || examine,
        component: 'Input',
        formItemProps: {
          rules: [
            {
              validator: (_rule, _value, callback) => {
                if (
                  !tableDialogStore.selectedItems ||
                  tableDialogStore.selectedItems.length === 0
                ) {
                  callback(new Error('该项为必填项'))
                  // callback()
                } else {
                  callback()
                }
              },
              trigger: 'click'
            }
          ]
        },
        componentProps: {
          class: 'invisible-input',
          readonly: true,
          slots: {
            prefix: () => {
              if (tableDialogStore.selectedItems && tableDialogStore.selectedItems.length > 0) {
                return tableDialogStore.selectedItems.map((item: SelectedItem) => (
                  <ElButton
                    size="small"
                    type="success"
                    plain
                    onClick={() => tableDialogStore.removeItem(item.id)}
                  >
                    {item.title}
                    <ElIcon>
                      <Close />
                    </ElIcon>
                  </ElButton>
                ))
              } else {
                // 处理selectedItems为空的情况，可能是返回null或者渲染一些提示信息
                return null
              }
            },
            suffix: () => {
              return (
                <ElButton
                  class="input-button"
                  size="small"
                  type="primary"
                  plain
                  onClick={() => {
                    const { allSchemas } = useCrudSchemas(
                      tableDialogCurdSchema ? tableDialogCurdSchema : []
                    )
                    tableDialogStore.openDialog()
                    tableDialogStore.setSchema(allSchemas)
                  }}
                >
                  {t('customer.choose')}
                </ElButton>
              )
            }
          }
        }
      },
      search: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.purchase_no
          }
        }
      },
      table: {
        hidden: true,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.cusid_value
          }
        }
      }
    },
    {
      field: 'pay_amount',
      label: t('payment.pay_amount'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: examine
        },
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'paid_amount',
      label: t('payment.paid_amount'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: true
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'owner',
      label: t('payment.owner'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: userStore.getUserInfo?.id,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: operatorList,
          filterable: true,
          limit: 1,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.owner_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.owner_value
          }
        }
      }
    },
    {
      field: 'payment_date',
      label: t('payment.payment_date'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'DatePicker',
        value: dayjs().format('YYYY-MM-DD'),
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD',
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'payment_account',
      label: t('payment.payment_account'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: 4,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: paymentaccountOption,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.payment_account_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.payment_account_value
          }
        }
      }
    },
    {
      field: 'pay_type',
      label: t('payment.pay_type'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: 1,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: paytypeOption,
          limit: 1,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.pay_type_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.pay_type_value
          }
        }
      }
    },
    {
      field: 'remark',
      label: t('payment.remark'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'attachment',
      label: t('payment.attachment'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          ...(!showUploadProof && {
            rules: [
              {
                required: true,
                message: t('common.required'),
                trigger: 'change'
              }
            ]
          }),
          slots: {
            default: (data: any) => {
              return (
                <div class="flex flex-col w-100%">
                  {!showUploadProof ? (
                    <>
                      <UploadFile
                        uploadDisabled={showUploadProof}
                        url={'/common/uploadFile'}
                        params={{ directory: 18 }}
                        limit={9}
                        multiple
                        drag
                        listType={'text'}
                        upload-file-button-name="点击上传或拖拽到此处上传"
                        button-link={true}
                        class="w-100%"
                        showFileList={true}
                        fileListMap={data.attachment_urls}
                        isSlot={false}
                        // @ts-ignore
                        uploadSuccessRes={({ fileList }: Record<string, any>) => {
                          const ids = fileList.map((item: any) =>
                            item.response ? item.response.data.id : item.id
                          )
                          const attachmentValue = ids.join(',')
                          setValues({ attachment: attachmentValue })
                          // 手动触发验证
                          nextTick(async () => {
                            if (formMethods?.getElFormExpose) {
                              const form = await formMethods.getElFormExpose()
                              form?.validateField('attachment')
                            }
                          })
                          // 单个文件上传成功，减少计数器
                          uploadingCount--
                          checkUploadComplete()
                        }}
                        // @ts-ignore
                        handleRemoveFile={(fileList: Record<string, any>) => {
                          const ids = fileList.map((item: any) =>
                            item.response ? item.response.data.id : item.id
                          )
                          const attachmentValue = ids.join(',')
                          setValues({ attachment: attachmentValue })
                          // 手动触发验证
                          nextTick(async () => {
                            if (formMethods?.getElFormExpose) {
                              const form = await formMethods.getElFormExpose()
                              form?.validateField('attachment')
                            }
                          })
                        }}
                        // @ts-ignore
                        downloadFile={(url: string) => {
                          window.open(url)
                        }}
                        // 上传前处理（包括点击和拖拽上传）
                        beforeUpload={() => {
                          // 增加上传计数器
                          uploadingCount++
                          // 如果是第一个文件，禁用保存按钮
                          if (uploadingCount === 1) {
                            uploading?.(true)
                          }
                          return true
                        }}
                        // 上传错误处理
                        onUploadError={() => {
                          // 单个文件上传失败，减少计数器
                          uploadingCount--
                          checkUploadComplete()
                        }}
                        // 文件超出限制时的处理
                        onExceed={() => {
                          // 超出限制，直接启用保存按钮（没有文件真正开始上传）
                          uploading?.(false)
                        }}
                      />
                      <div class="m-t-3 text-xs text-gray-800">最多上传 9 个文件</div>
                    </>
                  ) : (
                    <ElUpload
                      class="w-100%"
                      listType="text"
                      autoUpload={false}
                      fileList={data.attachment_urls}
                      showFileList={true}
                      onPreview={(file) => window.open(file.url)}
                    />
                  )}
                </div>
              )
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return (
              <UploadFile
                url={'/common/uploadFile'}
                limit={9}
                disabled={true}
                uploadDisabled={showUploadProof}
                isSlot={true}
                listType={'text'}
                fileListMap={data.attachment_urls}
                showFileList={true}
                downloadFile={(url: string) => {
                  if (!url) return
                  if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
                    return createImageViewer({
                      urlList: [url]
                    })
                  window.open(url)
                }}
              />
            )
          }
        }
      }
    },
    {
      field: 'responsible',
      label: t('payment.responsible'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: operatorList,
          filterable: true,
          limit: 1,
          disabled: examine
        },
        value: userStore.getUserInfo?.id
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.responsible_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.responsible_value
          }
        }
      }
    },
    {
      field: 'status',
      label: t('payment.paymentStatus'),
      search: {
        component: 'Select',
        componentProps: {
          options: statusOption
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.status_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.status_value
          }
        }
      }
    },
    {
      field: 'proof',
      label: t('payment.proof'),
      search: {
        hidden: true
      },
      form: {
        hidden: !showUploadProof,
        formItemProps: {
          ...(showUploadProof && {
            rules: [
              {
                required: true,
                message: t('common.required'),
                trigger: 'change'
              }
            ]
          }),
          slots: {
            default: (data: any) => {
              return (
                <div class="flex flex-col w-100%">
                  <UploadFile
                    uploadDisabled={!showUploadProof}
                    url={'/common/uploadFile'}
                    params={{ directory: 18 }}
                    limit={9}
                    multiple
                    drag
                    listType={'text'}
                    upload-file-button-name="点击上传或拖拽到此处上传"
                    button-link={true}
                    class="w-100%"
                    isSlot={false}
                    showFileList={true}
                    // @ts-ignore
                    uploadSuccessRes={({ fileList }: Record<string, any>) => {
                      const ids = fileList.map((item: any) =>
                        item.response ? item.response.data.id : item.id
                      )
                      const proofValue = ids.join(',')
                      setValues({ proof: proofValue })
                      // 手动触发验证
                      nextTick(async () => {
                        if (formMethods?.getElFormExpose) {
                          const form = await formMethods.getElFormExpose()
                          form?.validateField('proof')
                        }
                      })
                      // 单个文件上传成功，减少计数器
                      uploadingCount--
                      checkUploadComplete()
                    }}
                    // @ts-ignore
                    handleRemoveFile={(fileList: Record<string, any>) => {
                      const ids = fileList.map((item: any) =>
                        item.response ? item.response.data.id : item.id
                      )
                      const proofValue = ids.join(',')
                      setValues({ proof: proofValue })
                      // 手动触发验证
                      nextTick(async () => {
                        if (formMethods?.getElFormExpose) {
                          const form = await formMethods.getElFormExpose()
                          form?.validateField('proof')
                        }
                      })
                    }}
                    // @ts-ignore
                    downloadFile={(url: string) => {
                      window.open(url)
                    }}
                    // 上传前处理（包括点击和拖拽上传）
                    beforeUpload={() => {
                      // 增加上传计数器
                      uploadingCount++
                      // 如果是第一个文件，禁用保存按钮
                      if (uploadingCount === 1) {
                        uploading?.(true)
                      }
                      return true
                    }}
                    // 上传错误处理
                    onUploadError={() => {
                      // 单个文件上传失败，减少计数器
                      uploadingCount--
                      checkUploadComplete()
                    }}
                    // 文件超出限制时的处理
                    onExceed={() => {
                      // 超出限制，直接启用保存按钮（没有文件真正开始上传）
                      uploading?.(false)
                    }}
                  />
                  <div class="m-t-3 text-xs text-gray-800">最多上传 9 个文件</div>
                </div>
              )
            }
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return (
              <UploadFile
                url={'/common/uploadFile'}
                fileType={['png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx', 'pdf']}
                limit={9}
                disabled={true}
                uploadDisabled={true}
                isSlot={true}
                listType={'text'}
                fileListMap={data.proof_urls}
                showFileList={true}
                downloadFile={(url: string) => {
                  if (!url) return
                  if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
                    return createImageViewer({
                      urlList: [url]
                    })
                  window.open(url)
                }}
              />
            )
          }
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'recipient_account',
      label: t('payment.recipient_account'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          type: 'textarea',
          rows: 5,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return <div v-html={data.row.recipient_account}></div>
          }
        }
      }
    },
    {
      field: 'hash',
      label: t('payment.hash'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      }
    },
    {
      field: 'action',
      width: (actionButtonsTemplate?.length || 3) * 60 + 20 + 'px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  return {
    crudSchemas
  }
}
